package com.qyer.search.threading;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.qyer.search.model.mutable.PreferDestination;
import com.qyer.search.model.mutable.PreferKey;
import com.qyer.search.service.DMDBService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by tangzheng on 16/9/1.
 */
public class PreferCache {
  private static final Logger LOGGER = LoggerFactory
    .getLogger(PreferCache.class);

  private LoadingCache<PreferKey, PreferDestination> cache;
  private static class InnerHolder {
    private static final PreferCache INSTANCE = new PreferCache();
  }

  private PreferCache(){
    cache = CacheBuilder.newBuilder()
                        .maximumSize(1000)
                        .expireAfterWrite(5 * 60, TimeUnit.SECONDS)
                        .refreshAfterWrite(4 * 60, TimeUnit.SECONDS)
                        .initialCapacity(1000)
                        .recordStats()
                        .build(new CacheLoader<PreferKey, PreferDestination>() {
                          @Override public PreferDestination load(PreferKey preferKey) throws
                            Exception {
                            return DMDBService.getInstance().getDestPrefer(preferKey);
                          }
                        });
  }

  public static final PreferCache getInstance() {
    return InnerHolder.INSTANCE;
  }

  public static final LoadingCache<PreferKey, PreferDestination> getCache(){
    return InnerHolder.INSTANCE.cache;
  }

  public static final PreferDestination getCache(PreferKey preferKey) throws Exception{
    return PreferCache.getInstance().cache.get(preferKey);
  }

  public void setCache(LoadingCache<PreferKey, PreferDestination> cache) {
    this.cache = cache;
  }
}
